package com.example.springbootuploadanddownload.util;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.springbootuploadanddownload.domain.enums.FileTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileToMultipartFile implements MultipartFile {

    private final File file;

    public FileToMultipartFile(File file) {
        this.file = file;
    }

    @Override
    public String getName() {
        return file.getName();
    }

    @Override
    public String getOriginalFilename() {
        return file.getName();
    }

    @Override
    public String getContentType() {
        return "application/octet-stream";
    }

    @Override
    public boolean isEmpty() {
        return file.length() == 0;
    }

    @Override
    public long getSize() {
        return file.length();
    }

    @Override
    public byte[] getBytes() throws IOException {
        InputStream is = new FileInputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        return baos.toByteArray();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new FileInputStream(file);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (InputStream is = new FileInputStream(file);
             OutputStream os = new FileOutputStream(dest)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        }
    }

    public static String getSuffix(String fileName) throws Exception {
        if (StringUtils.isEmpty(fileName)) {
            throw new Exception("文件名为空。");
        }
        int begin = fileName.lastIndexOf(".")+1;
        int last = fileName.length();
        String suffix = fileName.substring(begin, last);
        suffix = suffix.toLowerCase();
        if (FileTypeEnum.getEnum(suffix) == null) {
            throw new Exception("暂不支持的文件类型。");
        } else {
            return suffix;
        }
    }
}
